#-*-coding: utf-8-*-

# Version: 0.1
# Author: Don Li <iedon@126.com>
# License: Copyright(c) 2017 Don.Li
# Summary:

import logging
import sys

def loglevel(level):
    level = str.lower(level)

    if str.startswith(level, 'd'):
        return logging.DEBUG
    elif str.startswith(level, 'i'):
        return logging.INFO
    elif str.startswith(level, 'w'):
        return logging.WARN
    elif str.startswith(level, 'e'):
        return logging.ERROR
    else:
        return logging.CRITICAL

class logger:
    _instance = None

    @staticmethod
    def add_handler(instanceLogger, level):
        console = logging.StreamHandler(sys.stdout)
        console.setLevel(level)

        formatter = logging.Formatter(
                '%(asctime)s.%(msecs)03d [%(process)d] [%(levelname)s] '
                '%(message)s (%(module)s.%(funcName)s,l:%(lineno)d)',
                '%F %T'
            )

        console.setFormatter(formatter)

        instanceLogger.setLevel(level)
        instanceLogger.addHandler(console)

    @staticmethod
    def initialize(app_name, level):
        logLevel = loglevel(level)
        logger._instance = logging.getLogger(app_name)
        logger.add_handler(logger._instance, logLevel)

        logging.raiseExceptions = 0

    def __getattr__(self, attr):
        return getattr(logger._instance, attr)

try:
    log
except NameError:
    log = logger()
